package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.app.Dialog;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.lxj.xpopup.XPopup;
import com.lxj.xpopup.core.AttachPopupView;
import com.lxj.xpopup.enums.PopupPosition;
import com.lxj.xpopup.interfaces.OnSelectListener;
import com.stark.picselect.entity.SelectMediaEntity;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.R;
import flc.ast.adapter.SelAudioAdapter;
import flc.ast.databinding.ActivityAudioManageBinding;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.MediaLoader;
import stark.common.basic.media.bean.AudioBean;
import stark.common.basic.utils.IntentUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.StkPermissionHelper;

public class AudioManageActivity extends BaseAc<ActivityAudioManageBinding> {

    private SelAudioAdapter selAudioAdapter;
    private boolean isEdit = true;
    private List<AudioBean> listDelete = new ArrayList<>();
    private AttachPopupView attachPopupView;
    private Dialog myDeleteDialog, myRenameDialog;
    private EditText editText;
    private int selPosition;


    @Override
    protected int onCreate() {
        return R.layout.activity_audio_manage;
    }

    @Override
    protected void initView() {
        mDataBinding.ivAudioManageBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        mDataBinding.rvAudioList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        selAudioAdapter = new SelAudioAdapter();
        selAudioAdapter.setEdit(isEdit);
        mDataBinding.rvAudioList.setAdapter(selAudioAdapter);
        selAudioAdapter.addChildClickViewIds(R.id.ivSelAudioItemEdit);
        selAudioAdapter.setOnItemChildClickListener(this);
        selAudioAdapter.setOnItemClickListener(this);

        mDataBinding.ivAudioManage.setOnClickListener(this);
        mDataBinding.ivManageCancel.setOnClickListener(this);
        mDataBinding.ivManageDelete.setOnClickListener(this);
        //重命名弹框
        renameDialog();
        //删除弹框
        deleteDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAudioManage:
                isEdit = false;
                selAudioAdapter.setEdit(isEdit);
                for (AudioBean validDatum : selAudioAdapter.getValidData()) {
                    validDatum.setSelected(false);
                }
                selAudioAdapter.notifyDataSetChanged();
                mDataBinding.ivAudioManage.setVisibility(View.GONE);
                mDataBinding.llManage.setVisibility(View.VISIBLE);
                break;
            case R.id.ivManageCancel://取消
                isEdit = true;
                selAudioAdapter.setEdit(isEdit);
                selAudioAdapter.notifyDataSetChanged();
                listDelete.clear();
                mDataBinding.ivAudioManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivManageDelete://删除
                if (isEdit || listDelete.size() != 0) {
                    myDeleteDialog.show();
                }
                break;
            //删除弹框
            case R.id.ivDialogDeleteConfirm:
                if (isEdit){
                    mContext.getContentResolver().delete(Uri.parse(selAudioAdapter.getItem(selPosition).getUri()), null, null);
                }else {
                    for (int i = 0; i < listDelete.size(); i++) {
                        //从此文件夹删除
                        mContext.getContentResolver().delete(Uri.parse(listDelete.get(i).getUri()), null, null);
                    }
                    isEdit = true;
                    selAudioAdapter.setEdit(isEdit);
                    listDelete.clear();
                }
                getData();
                myDeleteDialog.dismiss();
                ToastUtils.showShort(getString(R.string.delete_suc));
                mDataBinding.ivAudioManage.setVisibility(View.VISIBLE);
                mDataBinding.llManage.setVisibility(View.GONE);
                break;
            case R.id.ivDialogDeleteCancel:
                myDeleteDialog.dismiss();
                break;
            //重命名
            case R.id.ivDialogRenameConfirm:
                String name = editText.getText().toString();
                if (TextUtils.isEmpty(name)) {
                    ToastUtils.showShort(getText(R.string.please_input_video_name));
                    return;
                }
                FileUtils.rename(selAudioAdapter.getItem(selPosition).getPath(), name + "." + FileUtils.getFileExtension(selAudioAdapter.getItem(selPosition).getPath()));
                myRenameDialog.dismiss();
                editText.setText("");
                getData();
                break;
            case R.id.ivDialogRenameCancel:
                editText.setText("");
                myRenameDialog.dismiss();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (!isEdit) {
            if (selAudioAdapter.getItem(position).isSelected()) {
                selAudioAdapter.getItem(position).setSelected(false);
                listDelete.remove(selAudioAdapter.getItem(position));
                selAudioAdapter.notifyDataSetChanged();
            } else {
                listDelete.add(selAudioAdapter.getItem(position));
                selAudioAdapter.getItem(position).setSelected(true);
                selAudioAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onItemChildClick(@NonNull BaseQuickAdapter adapter, @NonNull View view, int position) {
        selPosition = position;
        switch (view.getId()) {
            case R.id.ivSelAudioItemEdit:
                attachPopupView = new XPopup.Builder(mContext)
                        .hasShadowBg(false)
//                            .isDestroyOnDismiss(true) //对于只使用一次的弹窗，推荐设置这个
//                        .isDarkTheme(true)
//                        .popupAnimation(PopupAnimation.NoAnimation) //NoAnimation表示禁用动画
//                        .isCenterHorizontal(true) //是否与目标水平居中对齐
//                        .offsetY(-60)
//                        .offsetX(80)
                        .popupPosition(PopupPosition.Left) //手动指定弹窗的位置
                        .atView(view)  // 依附于所点击的View，内部会自动判断在上方或者下方显示
                        .asAttachList(new String[]{getString(R.string.delete), getString(R.string.share),getString(R.string.edit), getString(R.string.rename)},
                                new int[]{R.drawable.ashanchu, R.drawable.afenx, R.drawable.abianji,R.drawable.achongmm},
                                new OnSelectListener() {
                                    @Override
                                    public void onSelect(int position, String text) {
                                        switch (position) {
                                            case 0:
                                                myDeleteDialog.show();
                                                break;
                                            case 1:
                                                IntentUtil.shareAudio(mContext, selAudioAdapter.getItem(selPosition).getPath());
                                                break;
                                            case 2:
                                                AudioEditActivity.audioPath=selAudioAdapter.getItem(selPosition).getPath();
                                                startActivity(AudioEditActivity.class);
                                                break;
                                            case 3:
                                                myRenameDialog.show();
                                                break;
                                        }
                                    }
                                }, 0, 0);
                ;
//                }
                attachPopupView.show();
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_AUDIO)
                .reqPermissionDesc(getString(R.string.get_music_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getData();
                    }

                    @Override
                    public void onDenied(boolean needGoSettings) {
                        ToastUtils.showShort(R.string.no_permission);
                    }
                }).request();
    }

    private void getData() {
        RxUtil.create(new RxUtil.Callback<List<AudioBean>>() {
            @Override
            public void doBackground(ObservableEmitter<List<AudioBean>> emitter) {
                List<AudioBean> audioBeans = MediaLoader.loadAudio();
                emitter.onNext(audioBeans);
            }

            @Override
            public void accept(List<AudioBean> audioBeanList) {
                if (audioBeanList != null) {
                    selAudioAdapter.setList(audioBeanList);
                    mDataBinding.rvAudioList.setVisibility(View.VISIBLE);
                    mDataBinding.ivAudioManageNoData.setVisibility(View.GONE);
                } else {
                    mDataBinding.rvAudioList.setVisibility(View.GONE);
                    mDataBinding.ivAudioManageNoData.setVisibility(View.VISIBLE);
                }
            }
        });
    }

    //删除弹框
    private void deleteDialog() {
        myDeleteDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_delete, null);
        myDeleteDialog.setContentView(inflate);
        myDeleteDialog.setCancelable(true);
        Window dialogWindow = myDeleteDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogDeleteCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogDeleteConfirm);
        TextView tip = inflate.findViewById(R.id.tvDialogDeleteTip);
        // 设置文本及其颜色
        StringBuffer str = new StringBuffer();
        str.append(getString(R.string.delete_tip1));
        str.append("<font color='#FF3838'>" + getString(R.string.delete_tip2) + "</font>");
        str.append(getString(R.string.delete_tip3));
        // 在文本控件中显示
        tip.setText(Html.fromHtml(str.toString(), getImageGetter(), null));
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    //重命名弹框
    private void renameDialog() {
        myRenameDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_rename, null);
        myRenameDialog.setContentView(inflate);
        myRenameDialog.setCancelable(true);
        Window dialogWindow = myRenameDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.CENTER);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 0.8);
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        ImageView cancel = inflate.findViewById(R.id.ivDialogRenameCancel);
        ImageView comp = inflate.findViewById(R.id.ivDialogRenameConfirm);
        editText = inflate.findViewById(R.id.etDialogFormatRename);
        cancel.setOnClickListener(this);
        comp.setOnClickListener(this);
    }

    private Html.ImageGetter getImageGetter() {
        return source -> {
            Drawable drawable = getDrawable(Integer.parseInt(source));
            drawable.setBounds(0, 0, 60, 60);
            return drawable;
        };
    }

}